package com.google.code.cisx.servlets;

import com.google.code.cisx.store.StoreModule;
import com.google.inject.Guice;
import com.google.inject.Injector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Application Lifecycle Listener implementation class
 * GuiceServletContextListener
 * 
 */
public final class GuiceServletContextListener implements ServletContextListener {
  
  /**
   * Commons Logging.
   */
  private static final Log log = LogFactory.getLog(GuiceServletContextListener.class);

  /**
   * @see ServletContextListener#contextDestroyed(ServletContextEvent)
   */
  public void contextDestroyed(ServletContextEvent event) {
    event.getServletContext().removeAttribute(ServletContextConstants.KEY_GUICE_INJECTOR);
  }

  /**
   * @see ServletContextListener#contextInitialized(ServletContextEvent)
   */
  public void contextInitialized(ServletContextEvent event) {
    if (log.isInfoEnabled())
      log.info("Initializing Guice module: " + StoreModule.class.getName());
    // setup Guice bindings
    StoreModule storeModule = new StoreModule();
    Injector injector = Guice.createInjector(storeModule);
    injector.injectMembers(this);

    // register the injector in servlet context
    Injector registeredInjector = (Injector) event.getServletContext().getAttribute(
        ServletContextConstants.KEY_GUICE_INJECTOR);
    if (null != registeredInjector)
      throw new IllegalStateException(Injector.class.getName()
          + " is already registered in the ServletContext");
    // else register
    event.getServletContext().setAttribute(ServletContextConstants.KEY_GUICE_INJECTOR, injector);
    if (log.isInfoEnabled())
      log.info("Guice module initialised!");
  }
}
